package com.ktwlsoft.fundmanage.service.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktwlsoft.fundmanage.domain.entity.sms.*;
import com.ktwlsoft.fundmanage.domain.repository.sms.SmsLogRepository;
import com.ktwlsoft.fundmanage.domain.repository.sms.SmsTemplateRepository;
import com.ktwlsoft.fundmanage.payload.BaseResult;
import com.ktwlsoft.fundmanage.payload.IAccountUser;
import com.ktwlsoft.fundmanage.payload.ResultType;
import com.ktwlsoft.fundmanage.utils.KeyWorkerUtil;
import com.ktwlsoft.fundmanage.utils.SmsHelperUtils;
import com.ktwlsoft.fundmanage.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 短信
 *
 * @author Name on 2019/9/6 14:58
 * @version 1.0
 */
@Service
public class SmsService {

    @Autowired
    private SmsLogRepository smsLogRepository;
    @Autowired
    private SmsTemplateRepository smsTemplateRepository;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 短信发送
     *
     * @param model model
     * @return ResponseEntity<Object>
     */
    public BaseResult<?> sendSms(SendSms model) {
        if (model.getSmsTemplateEncoded() == null || "".equals(model.getSmsTemplateEncoded().trim())) {
            return BaseResult.body(model, ResultType.BUSINESS_ERROR).withMessage("短信模板编码不能为空");
        }
        if (model.getPhoneNumbers().length <= 0) {
            return BaseResult.body(model, ResultType.BUSINESS_ERROR).withMessage("待发送手机号不能为空");
        }
        String templateParam = "";
        if (model.getParamMap().size() > 0) {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(model.getParamMap()));
            templateParam = jsonObject.toString();
        }
        //短信模板信息
        SmsTemplate template = smsTemplateRepository.findByEncoded(model.getSmsTemplateEncoded());
        if(template == null){
            return BaseResult.body(model, ResultType.BUSINESS_ERROR).withMessage("该模板数据不存在");
        }
        //短信日志
        SmsLog smsLog = new SmsLog();
        smsLog.setId(KeyWorkerUtil.nextId());
        smsLog.setMobile(joinArrayWithSeparator(model.getPhoneNumbers(), ","));
        smsLog.setDisplayContent(replaceContenParam(template.getTemplateText(), model.getParamMap()));
        smsLog.setContent(templateParam);
        IAccountUser userData = UserUtils.getUser();
        smsLog.setAccountId(userData.getUserId() != null?userData.getAccountId():"");
        smsLog.setCreateTime(new Date());
        switch (model.getSmsChannel()) {
            case "1":
                SmsParam smsRequest = new SmsParam();
                smsRequest.setAccessKeyId(smsConfig.getAccessKeyId());
                smsRequest.setAccessKeySecret(smsConfig.getAccessKeySecret());
                smsRequest.setSignName(template.getTemplateSign());
                smsRequest.setTemplateCode(template.getTemplateCode());
                smsRequest.setPhoneNumbers(joinArrayWithSeparator(model.getPhoneNumbers(), ","));
                smsRequest.setTemplateParam(templateParam);
                boolean result = SmsHelperUtils.sendSms(smsRequest);
                if (!result) {
                    smsLog.setStatus(0);
                    smsLog.setRemark(smsRequest.getErrorMsg());
                    smsLog.setContent(JSONObject.toJSONString(smsRequest));
                    smsLogRepository.save(smsLog);
                    return BaseResult.body(model, ResultType.BUSINESS_ERROR).withMessage("短信发送失败：" + smsRequest.getErrorMsg());
                }
                break;
            default:
                return BaseResult.body(model, ResultType.BUSINESS_ERROR).withMessage("该短信渠道未集成");
        }
        smsLog.setStatus(1);
        smsLogRepository.save(smsLog);
        return BaseResult.body(model, ResultType.BUSINESS_SUCCESS);
    }

    /**
     * 替换内容参数
     *
     * @param content 待替换内容
     * @param paramMap 传入参数
     * @return String
     */
    private String replaceContenParam(String content, Map<String, String> paramMap) {
        String resultStr = content;
        if (paramMap != null && paramMap.size() > 0) {
            for (Map.Entry<String, String> item : paramMap.entrySet()) {
                resultStr = resultStr.replace("${" + item.getKey() + "}", item.getValue());
            }
        }
        return resultStr;
    }

    private static String joinArrayWithSeparator(String[] strings, String separator) {
        StringBuilder sb = new StringBuilder();
        for (String s : strings) {
            sb.append(s);
            sb.append(separator);
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}